//
//  MLMultiSelectButton.m
//  TycoonSale
//
//  Created by molon on 15/8/6.
//  Copyright (c) 2015年 molon. All rights reserved.
//

#import "MLMultiSelectButton.h"
#import "MLKitDefine.h"
#import "UITableViewCell+MLKit.h"
#import "UIWindow+MLKit.h"
#import "SelectItem.h"

#define kDimmingBlackViewAnimateDuration .25f
#define kTabelViewHeight 250.0f

@interface MLMultiSelectButton()<UITableViewDataSource,UITableViewDelegate>

@property(strong,nonatomic,readwrite) UIToolbar *inputAccessoryView;
@property(strong,nonatomic,readwrite) UITableView *inputView;
@property(nonatomic,strong) UIView *dimmingBlackView;
@property(nonatomic,strong) UILabel *inputTitleLabel;

@end

@implementation MLMultiSelectButton


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        [self setUp];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setUp];
    }
    return self;
}


- (void)dealloc
{
    [self hideBlackOverlayView];
}

- (void)setUp
{
    //添加一个点击可成为第一响应者的Target
    [super addTarget:self action:@selector(defaultTarget) forControlEvents:UIControlEventTouchUpInside];
}

//覆盖了，不让用户外部可以添加Target
- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents
{
    return;
}

#pragma mark - input
- (UIToolbar *)inputAccessoryView
{
    if(!_inputAccessoryView){
        UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, self.inputView.frame.size.width, 44)];
        
        NSString *title = @"取消";
        if (self.delegate&&[self.delegate respondsToSelector:@selector(customCancelTitle)]) {
            title = [self.delegate customCancelTitle];
        }
        UIBarButtonItem *left = [[UIBarButtonItem alloc]initWithTitle:title style:UIBarButtonItemStyleDone target:self action:@selector(cancel)];
        UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(done)];
        
        if (self.dontDisplayDimmingView) {
            toolBar.items = @[spaceItem,right];
        }else{
            toolBar.items = @[left,spaceItem,right];
        }
        
        toolBar.backgroundColor = [UIColor whiteColor];
        _inputAccessoryView = toolBar;
    }
    return _inputAccessoryView;
}

- (UITableView *)inputView
{
    if(!_inputView)
    {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kTabelViewHeight)];
        tableView.scrollsToTop = NO;
        tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        tableView.delegate = self;
        tableView.dataSource = self;
        [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:[UITableViewCell cellReuseIdentifier]];
        
        _inputView = tableView;
    }
    return _inputView;
}

- (UILabel *)inputTitleLabel
{
    if (!_inputTitleLabel) {
        UILabel *label = [[UILabel alloc]init];
        label.backgroundColor = [UIColor clearColor];
        label.textColor = [UIColor blackColor];
        label.textAlignment = NSTextAlignmentCenter;
        
        [self.inputAccessoryView addSubview:label];
        
        _inputTitleLabel = label;
        
        _inputTitleLabel.frame = self.inputAccessoryView.bounds;
    }
    return _inputTitleLabel;
}

#pragma mark - setter
- (void)setItems:(SelectItemArray *)items
{
    _items = items;
    
    [self.inputView reloadData];
    if (items.count>0) {
        [self.inputView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    }
}

- (void)setDontDisplayDimmingView:(BOOL)dontDisplayDimmingView
{
    _dontDisplayDimmingView = dontDisplayDimmingView;
    
    self.inputAccessoryView = nil;
}

- (void)setInputTitle:(NSString *)inputTitle
{
    _inputTitle = [inputTitle copy];
    self.inputTitleLabel.text = inputTitle;
}


#pragma mark - tableView
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    SelectItem *item = self.items[indexPath.row];
    item.selected = !item.selected;
    
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[UITableViewCell cellReuseIdentifier] forIndexPath:indexPath];
    cell.textLabel.font = FONT(14.0f);
    
    SelectItem *item = self.items[indexPath.row];
    cell.imageView.image = [UIImage imageNamed:item.selected?MLKIT_BUNDLE_FILE(@"多选-已选"):MLKIT_BUNDLE_FILE(@"多选-未选")];
    cell.textLabel.text = item.name;
    
    return cell;
}

#pragma mark - layout
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    self.inputTitleLabel.frame = self.inputAccessoryView.bounds;
}

#pragma mark - event
- (void)defaultTarget
{
    if (self.delegate&& [self.delegate respondsToSelector:@selector(shouldBecomeFirstResponderWithMultiSelectButton:)]) {
        if (![self.delegate shouldBecomeFirstResponderWithMultiSelectButton:self]) {
            return;
        }
    }
    
    [self becomeFirstResponder];
}

-(void)cancel
{
    if (self.delegate&&[self.delegate respondsToSelector:@selector(customClickCancle)]) {
        [self.delegate customClickCancle];
    }else{
        [self resignFirstResponder];
    }
}

- (void)done
{
    if (self.delegate&&[self.delegate respondsToSelector:@selector(doneWithMultiSelectButton:)]) {
        [self.delegate doneWithMultiSelectButton:self];
    }
    
    [self resignFirstResponder];
}

- (void)tapDimmingBlackViewWithTapGesture:(UITapGestureRecognizer*)tapGesture
{
    [self resignFirstResponder];
}

#pragma mark - responder and blackOverlayView
- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (BOOL)becomeFirstResponder
{
    if ([self isFirstResponder]) {
        return YES;
    }
    
    BOOL result = [super becomeFirstResponder];
    if (result) {
        if (self.dimmingBlackView) {
            [self.dimmingBlackView removeFromSuperview];
            self.dimmingBlackView = nil;
        }
        if (!self.dontDisplayDimmingView) {
            //添加一个蒙版黑色View
            UIWindow* window = [UIWindow currentNormalWindow];
            UIView *blackView = [[UIView alloc]initWithFrame:window.bounds];
            blackView.backgroundColor = [UIColor blackColor];
            blackView.userInteractionEnabled = YES;
            [window addSubview:self.dimmingBlackView = blackView];
            
            //对其添加点击事件
            UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]init];
            tapGesture.numberOfTapsRequired = 1;
            tapGesture.numberOfTouchesRequired = 1;
            [tapGesture addTarget:self action:@selector(tapDimmingBlackViewWithTapGesture:)];
            [self.dimmingBlackView addGestureRecognizer:tapGesture];
            
            blackView.layer.opacity = 0.09f;
            [UIView animateWithDuration:kDimmingBlackViewAnimateDuration animations:^{
                blackView.layer.opacity = 0.30f;
            }];
        }
        
        if (self.delegate&&[self.delegate respondsToSelector:@selector(becomeFirstResponderWithMultiSelectButton:)]) {
            [self.delegate becomeFirstResponderWithMultiSelectButton:self];
        }
        
    }
    return result;
}

- (BOOL)resignFirstResponder
{
    BOOL result = [super resignFirstResponder];
    if (result) {
        [self hideBlackOverlayView];
        
        if (self.delegate&&[self.delegate respondsToSelector:@selector(resignFirstResponderWithMultiSelectButton:)]) {
            [self.delegate resignFirstResponderWithMultiSelectButton:self];
        }
    }
    return result;
}

- (void)hideBlackOverlayView
{
    if (self.dimmingBlackView) {
        UIView *dimmingBlackView = self.dimmingBlackView;
        self.dimmingBlackView = nil;
        [UIView animateWithDuration:kDimmingBlackViewAnimateDuration animations:^{
            dimmingBlackView.layer.opacity = 0.01f;
        } completion:^(BOOL finished) {
            [dimmingBlackView removeFromSuperview];
        }];
    }
}

#pragma mark - touchUpInSide
- (void)touchUpInSide
{
    [self defaultTarget];
}

@end
